package cj.web.sc.controllers;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.paoding.rose.web.annotation.Param;
import net.paoding.rose.web.annotation.Path;
import net.paoding.rose.web.annotation.rest.Get;
import net.paoding.rose.web.annotation.rest.Post;
import net.paoding.rose.web.var.Model;
import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;

import cj.utils.Constants;
import cj.web.cc.controllers.BaseController;
import cj.web.constants.MemuEnum;
import cj.web.constants.OrderByPriceEnum;
import cj.web.sc.dao.GoodsDAO;
import cj.web.sc.dao.OrderDAO;
import cj.web.uc.dao.LoginDAO;

@Path("goodsPc")
public class GoodsPcController extends BaseController{
	@Autowired
	private GoodsDAO goodsDao;
	@Autowired
	private OrderDAO orderDao;
	@Autowired
	private LoginDAO memberDAO;
	
	
	public final static String yt="";//原图1420*960
	public final static String pcs="pcs_";//缩图660*480
	public final static String pcss="pcss_";//缩图156*116
	
	/**
	 * 书店首页
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@Get("home")
	public String home(Model model,HttpServletRequest request,
			@Param("state")String state,HttpServletResponse response) throws Exception{
		//------------------------------获取传递过来的game 和 参赛证号
		String urlGameId = "";
		String urlCode = "";
		if(state!=null && !"".equals(state)){
			urlGameId = state.split(URLPARAMS)[0].toString();
			urlCode = state.split(URLPARAMS)[1].toString();
		}
		
		setCookie(response, "urlGameId", urlGameId);
		setCookie(response, "urlCode", urlCode);
		//------------------------------获取传递过来的game 和 参赛证号
		
		String memberId = getCookieValueByName(request, "memberId");
		
		if(memberId!=null && !"".equals(memberId)){
			//购物车列表
			List<Map> cartObjs = orderDao.cartByBuyerId(Integer.parseInt(memberId));
			model.add("cartObjs", cartObjs);
			model.add("cartSize", cartObjs.size());
			BigDecimal discntPriceSum = new BigDecimal("0");
			for(Map obj:cartObjs){
				BigDecimal discntPrice = new BigDecimal(obj.get("discntPrice").toString());
				BigDecimal count = new BigDecimal(obj.get("count").toString());
				BigDecimal bignum3 = discntPrice.multiply(count);  //discntPrice*count
				discntPriceSum =  discntPriceSum.add(bignum3);   //sum
			}
			model.add("discntPrice", discntPriceSum);
		}else{
			model.add("cartObjs", null);
			model.add("cartSize", 0);
			model.add("discntPrice", 0);
		}
		model.add("currentTopMemu", MemuEnum.memuccsd);
		return "/views/mallPC/index.vm";
	}
	
	/**
	 * 商品列表
	 * @param orPrice
	 * @return
	 */
	@Post("list")
	public String list(@Param("orPrice")String orPrice){
		if(orPrice==null || "".equals(orPrice)){
			orPrice=OrderByPriceEnum.ASC.getName();
		}
		
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		
		List<Map> objs = goodsDao.goodsList(orPrice);
		for(Map rep:objs){
			String image = rep.get("image").toString().replace("ss_", yt);
			rep.put("image", image);
		}
		
		jo.put("list", objs);
		return "@" + jo.toString();
	}
	
	/**
	 * 商品多属性详情
	 * @param model
	 * @param goodsId
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@Get("items")
	public String items(Model model, @Param("id")int goodsId, HttpServletRequest request) throws Exception{
		List<Map> goodsObj = goodsDao.getGoodsById(goodsId);
		List<Map> itemObjs = goodsDao.getVltItemsByGoodsId(goodsId);
		model.add("currentTopMemu", MemuEnum.memuccsd);
		//购物车列表
		returnCart(model, request, goodsId, null);
		
		//商品详情
		if(goodsObj != null && goodsObj.size() > 0 && 
				itemObjs!=null && itemObjs.size() > 0){
			
			returnGoodDetail(model, goodsId, goodsObj, itemObjs);
			return "/views/mallPC/goodsDetail.vm";
		}
		else{
			model.add("warning", "该商品已下架");
			return "/views/mallPC/cartNothing.vm";
		}
	}
	
	/**
	 * 商品多属性详情
	 * @param model
	 * @param goodsId
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@Get("itemsZC")
	public String itemsZC(Model model, @Param("id")int goodsId, HttpServletRequest request) throws Exception{
		List<Map> goodsObj = goodsDao.getGoodsById(goodsId);
		List<Map> itemObjs = goodsDao.getVltItemsByGoodsId(goodsId);
		model.add("currentTopMemu", MemuEnum.memuccsd);
		//购物车列表
		returnCart(model, request, goodsId, null);
		
		//商品详情
		if(goodsObj != null && goodsObj.size() > 0 && 
				itemObjs!=null && itemObjs.size() > 0){
			
			returnGoodDetail(model, goodsId, goodsObj, itemObjs);
			return "/views/mallPC/goodsZCDetail.vm";
		}
		else{
			model.add("warning", "该商品已下架");
			return "/views/mallPC/cartNothing.vm";
		}
	}
	
	/**
	 * 商品多属性详情
	 * @param model
	 * @param goodsId
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@Get("itemsByitemId")
	public String itemsByitemId(Model model, @Param("itemId")int goodsItemId, HttpServletRequest request) throws Exception{
		
		List<Map> goodsItemObj = goodsDao.getGoodsItemById(goodsItemId);
		if(goodsItemObj!=null && goodsItemObj.size()>0){
			//商品ID
			int goodsId = Integer.parseInt(goodsItemObj.get(0).get("goodsId").toString());
			List<Map> goodsObj = goodsDao.getGoodsById(goodsId);
			List<Map> itemObjs = goodsDao.getVltItemsByGoodsId(goodsId);
			model.add("currentTopMemu", MemuEnum.memuccsd);
			//购物车列表
			returnCart(model, request, goodsId, null);
			
			//商品详情
			if(goodsObj != null && goodsObj.size() > 0 && 
					itemObjs!=null && itemObjs.size() > 0){
				
				returnGoodDetail(model, goodsId, goodsObj, itemObjs);
				return "/views/mallPC/goodsDetail.vm";
			}
			else{
				model.add("warning", "该商品已下架");
				return "/views/mallPC/cartNothing.vm";
			}
		}else{
			model.add("warning", "该商品已下架");
			return "/views/mallPC/cartNothing.vm";
		}
		
	}
	
	/**
	 * 商品多属性详情
	 * @param model
	 * @param goodsId
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@Get("itemsZCByitemId")
	public String itemsZCByitemId(Model model, @Param("itemId")int goodsItemId, HttpServletRequest request) throws Exception{
		
		List<Map> goodsItemObj = goodsDao.getGoodsItemById(goodsItemId);
		if(goodsItemObj!=null && goodsItemObj.size()>0){
			//商品ID
			int goodsId = Integer.parseInt(goodsItemObj.get(0).get("goodsId").toString());
			List<Map> goodsObj = goodsDao.getGoodsById(goodsId);
			List<Map> itemObjs = goodsDao.getVltItemsByGoodsId(goodsId);
			model.add("currentTopMemu", MemuEnum.memuccsd);
			//购物车列表
			returnCart(model, request, goodsId, null);
			
			//商品详情
			if(goodsObj != null && goodsObj.size() > 0 && 
					itemObjs!=null && itemObjs.size() > 0){
				
				returnGoodDetail(model, goodsId, goodsObj, itemObjs);
				return "/views/mallPC/goodsZCDetail.vm";
			}
			else{
				model.add("warning", "该商品已下架");
				return "/views/mallPC/cartNothing.vm";
			}
		}else{
			model.add("warning", "该商品已下架");
			return "/views/mallPC/cartNothing.vm";
		}
		
	}
	
	/**
	 * 首页跳转去结算
	 * @param model
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@Get("toOrderComfig")
	public String toOrderComfig(Model model, HttpServletRequest request) throws Exception{
		
		String memberId = getCookieValueByName(request, "memberId");
		//购物车列表
		List<Map> cartObjs = orderDao.cartByBuyerId(Integer.parseInt(memberId));
		
		String goodsItemIds ="";//商品项ID
		String counts ="";//商品数量ID
		
		for(Map rep:cartObjs){
			int status =Integer.parseInt(rep.get("status").toString());
			if(status==1){//上架状态
				goodsItemIds += rep.get("goodsItemId")+",";
				counts += rep.get("count")+",";
			}
		}
		
		return "r:../orderPc/orderConfirm?goodsItemIds="+goodsItemIds.substring(0, goodsItemIds.length()-1)+"&counts="+counts.substring(0, counts.length()-1);
	}
	
	/**
	 * 商品在购物车中多属性详情
	 * @param model
	 * @param goodsId
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@Get("itemsCart")
	public String items(Model model, @Param("id")int goodsId, @Param("itemId")int itemId, HttpServletRequest request) throws Exception{
		List<Map> goodsObj = goodsDao.getGoodsById(goodsId);
		List<Map> itemObjs = goodsDao.getVltItemsByGoodsId(goodsId);
		model.add("currentTopMemu", MemuEnum.memuccsd);
		//购物车列表
		returnCart(model, request, goodsId, itemId);
		
		//商品详情
		if(goodsObj != null && goodsObj.size() > 0 && 
				itemObjs!=null && itemObjs.size() > 0){
			
			returnGoodDetail(model, goodsId, goodsObj, itemObjs);
			return "/views/mallPC/goodsCartDetail.vm";
		}
		else{
			model.add("warning", "该商品已下架");
			return "/views/mallPC/cartNothing.vm";
		}
	}
	
	/**
	 * 商品详情
	 * @param model
	 * @param goodsId
	 * @param goodsObj
	 * @param itemObjs
	 */
	private void returnGoodDetail(Model model,int goodsId,List<Map> goodsObj,List<Map> itemObjs){
		//商品属性名称&图片
		for(Map map : itemObjs){
			map.put("propValueNames", map.get("propValueNames").toString().replaceAll(",", ""));
			String image = map.get("image").toString().replace("ss_", yt);
			map.put("image", image);
		}
		
		//商品轮播图
		List<Map> banner = goodsDao.getBannerByGoodsId(goodsId);
		for(Map rep:banner){
			String image = rep.get("path").toString().replace("s_", yt);
			rep.put("path", image);
		}
		
		//商品图片
		String goodsImage = goodsObj.get(0).get("image").toString().replace("ss_", yt);
		goodsObj.get(0).put("image", goodsImage);
		
		model.add("Goods",goodsObj.get(0));
		model.add("Items",itemObjs);
		model.add("Banner",banner);
	}
	
	/**
	 * 购物车列表
	 * @param model
	 * @param request
	 * @param goodsId
	 * @param itemId
	 */
	private void returnCart(Model model, HttpServletRequest request, Integer goodsId ,Integer itemId){
		//购物车列表
		String memberId = getCookieValueByName(request, "memberId");
		if(memberId!=null && !"".equals(memberId)){
			//购物车列表
			List<Map> cartObjs = orderDao.cartByBuyerId(Integer.parseInt(memberId));
			model.add("cartObjs", cartObjs);
			model.add("cartSize", cartObjs.size());
			BigDecimal discntPriceSum = new BigDecimal("0");
			for(Map obj:cartObjs){
				BigDecimal discntPrice = new BigDecimal(obj.get("discntPrice").toString());
				BigDecimal count = new BigDecimal(obj.get("count").toString());
				BigDecimal bignum3 = discntPrice.multiply(count);  //discntPrice*count
				discntPriceSum =  discntPriceSum.add(bignum3);   //sum
				model.add("discntPrice", discntPriceSum);
				
				if(itemId!=null){
					if(goodsId==Integer.parseInt(obj.get("goodsId").toString()) && itemId==Integer.parseInt(obj.get("goodsItemId").toString())){
						model.add("goodsItemId", itemId);//商品属性ID
						model.add("goodsCount", obj.get("count").toString());//商品数量
					}
				}
			}
		}else{
			model.add("cartObjs", null);
			model.add("cartSize", 0);
			model.add("discntPrice", 0);
			if(itemId!=null){
				model.add("goodsItemId", itemId);//商品属性ID
				model.add("goodsCount", 1);//商品数量
			}
		}
	}
	
	/**
	 * 加入购物车
	 * @param goodsId
	 * @param sellerId
	 * @param goodsItemId
	 * @param count
	 * @param retPg
	 * @param request
	 * @param response
	 * @return
	 */
	@Post("intoCart")
	public String intoCart(@Param("goodsId")int goodsId, @Param("sellerId")int sellerId,
			@Param("goodsItemId")int goodsItemId,@Param("count")int count, 
			HttpServletRequest request,HttpServletResponse response){
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		
		if( isLogin(request) ){
			List<Map> goodsItem = goodsDao.getGoodsItemById(goodsItemId);
			
			if(goodsItem != null && goodsItem.size() > 0 ){   //验证库存
				int inventory = Integer.parseInt(goodsItem.get(0).get("inventory").toString());
				if(inventory < count){
					jo.put("rtnMsg", "库存不足");
					jo.put("returnFlag", Constants.returnObj.returnFlag_repeat);
					return "@" + jo.toString();
				}
				else{
					String phone = getCookieValueByName(request, "phone");
					int buyerId = memberDAO.getBuyerId(phone);
					
					List<Map> Obj = goodsDao.isInCart(buyerId, goodsItemId);
					
					if(Obj != null && Obj.size() > 0){
						int origCnt = Integer.parseInt(Obj.get(0).get("count").toString());
						if( inventory < count + origCnt ){
							jo.put("rtnMsg", "库存不足");
							jo.put("returnFlag", Constants.returnObj.returnFlag_repeat);
							return "@" + jo.toString();
						}
						else{
							goodsDao.updateCart(count,buyerId,goodsItemId);
						}
					}
					else{
						goodsDao.insertCart(buyerId, sellerId, goodsItemId, count, phone);
					}
				}
			}
			else{
				jo.put("rtnMsg", "该商品已下架");
				jo.put("returnFlag", Constants.returnObj.returnFlag_repeat);
				return "@" + jo.toString();
			}
		}
		else{
			String returnPage = "/goodsPc/items?id=" + goodsId;
			setCookie(response, "returnPage", returnPage);//订单
			jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
			return "@" + jo.toString();
		}
		
		return "@" + jo.toString();
	}
}